package com.jtjrenren.android.taxi.passenger.core.main;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.jtjrenren.android.taxi.passenger.Constants;
import com.jtjrenren.android.taxi.passenger.R;
import com.jtjrenren.android.taxi.passenger.base.BaseApplication;
import com.jtjrenren.android.taxi.passenger.bean.AddressInfo;
import com.jtjrenren.android.taxi.passenger.bean.ApiCarListArea;
import com.jtjrenren.android.taxi.passenger.bean.Order;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiCommonResult;
import com.jtjrenren.android.taxi.passenger.bean.api.ESpecarCost;
import com.jtjrenren.android.taxi.passenger.bean.event.LocationEvent;
import com.jtjrenren.android.taxi.passenger.bean.event.RLoginEvent;
import com.jtjrenren.android.taxi.passenger.bean.protocl.OtherLoginResponse;
import com.jtjrenren.android.taxi.passenger.manger.AppManger;
import com.jtjrenren.android.taxi.passenger.manger.api.ApiWorks;
import com.jtjrenren.android.taxi.passenger.utils.AppConfig;
import com.jtjrenren.android.taxi.passenger.utils.ModuleUtils;
import com.library.mvp.presenter.BasePresenter;
import com.library.utils.AppUtils;
import com.library.utils.LogUtil;
import com.library.utils.SpUtils;
import com.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2016/9/12.
 */

public class MainPresenterImpl extends BasePresenter<MainView, MainInteractor> implements MainPresenter {
    public static final int MODE_MAP_LOC = 200; //地图中心位置随地图定位改变
    public static final int MODE_MAP_DIY = 201;//地图中心位置为个人设置

    private GeoCoder geoCoder; //百度地图反地理编码

    private AddressInfo endAddressInfo; //结束点位置信息
    private AddressInfo currentLocAddr; //地图当前的中心点的位置信息
    private Order currentOrder;//当前的订单
    private int currentMapMode = MODE_MAP_LOC;  //当前地图刷新模式 定位or手动改变
    private LatLng lastLatlngLoc; //上次定位的经纬度
    private boolean softSelected = false, businessSelected = false,
            luxurySelected = false, fristRefreshMap = false, isSsOrder = false;

    public MainPresenterImpl(MainView view) {
        super(view);
    }

    @Override
    public void sub() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void unSub() {
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void destory() {
        if (geoCoder != null)
            geoCoder.destroy();
        unSub();
    }

    @Override
    public void initGeocoder() {
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                if (!fristRefreshMap) {
                    fristRefreshMap = true;
                    AppManger.getInstance().requestLoc();
                }
                if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR)
                    return;
                String showLoc = ModuleUtils.getMapShowLocMsgByRr(reverseGeoCodeResult);

                currentLocAddr.setName(showLoc);
                currentOrder.setStartAddr(showLoc);

                view.refreshStartMsg(showLoc);

                ygCost();

            }
        });
    }

    @Override
    public void checkGps() {
        if (((boolean) SpUtils.getParam(AppManger.getInstance().getContext(), Constants.SP_SETTING_GPS_SWITCH, true))
                && !AppUtils.isGPSLaunched(AppManger.getInstance().getContext())) {
            view.showGpsTip();
        }
    }

    @Override
    public void initMain() {
        currentLocAddr = new AddressInfo();
        endAddressInfo = new AddressInfo();
        currentOrder = new Order();

        initGeocoder();
        checkGps();

        LatLng lastLatLng = AppConfig.getLastRemLocation(AppManger.getInstance().getContext());
        view.refreshBdMapCenter(lastLatLng);
        mapCenterChange(lastLatLng);


    }

    @Override
    public void initView() {
        view.refreshAfterLogin(AppManger.getInstance().user);


        AppManger.getInstance().requestLoc();
    }

    @Override
    public void refreshLocType(int type) {
        currentMapMode = type;
        if (type == MODE_MAP_LOC && lastLatlngLoc != null) {
            view.refreshBdMapCenter(lastLatlngLoc);
        }
    }

    @Override
    public void refreshAreaCarList(int carType, LatLng latLng) {
        interactor.getAreaCarList(carType, latLng.latitude + "", latLng.longitude + "", new ApiWorks.ResponseListener<ApiCarListArea>() {
            @Override
            public void onResponse(ApiCarListArea carListArea) {
                view.clearCarListOnMap();

                if (carListArea != null && carListArea.getCarList() != null && carListArea.getCarList().size() > 0) {
                    view.refreshCarListOnMap(currentOrder.getOrderCarType(), carListArea.getCarList());
                }
            }
        });
    }

    @Override
    public void orderTypeChange(int type) {
        if (type == Constants.CARTYPE_TAXI) {
            currentOrder.setOrderCarType(Constants.CARTYPE_TAXI);
            currentOrder.setCarType(0);

            view.selectTaxiType();
            view.showSpecarPayView(false);
        } else if (type == Constants.CARTYPE_SPECAR) {
            currentOrder.setOrderCarType(Constants.CARTYPE_SPECAR);

            view.selectSpeCar();
            if (!StringUtils.isEmpty(currentOrder.getStartAddr()) && !StringUtils.isEmpty(currentOrder.getEndAddr()))
                view.showSpecarPayView(true);
        }

        if (!StringUtils.isEmpty(currentLocAddr.getLati()) && !StringUtils.isEmpty(currentLocAddr.getLongi())) {
            LatLng latLng = new LatLng(Double.parseDouble(currentLocAddr.getLati()), Double.parseDouble(currentLocAddr.getLongi()));
            refreshAreaCarList(type, latLng);
        }

    }

    @Override
    public void showCostDetails() {
        String bookDate = currentOrder.getBookDate();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        if (!StringUtils.isEmpty(bookDate)) {
            try {
                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyMMddHHmmss");
                date = simpleDateFormat2.parse(bookDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        bookDate = simpleDateFormat.format(date);

        String url = ModuleUtils.getCostDetailsUrl(currentOrder.getStartAddr(), currentOrder.getStartLat()
                , currentOrder.getStartLng(), currentOrder.getEndAddr(), currentOrder.getEndLat(), currentOrder.getEndLng()
                , getEastCostType() + "", bookDate, AppManger.getInstance().user.getWorkNo());

        view.goWebPage("", url, false);
    }

    @Override
    public void orderSpecarTypeChange(int type) {
        LogUtil.log("order", "约租车状态改变：" + type);
        softSelected = false;
        businessSelected = false;
        luxurySelected = false;
        if (type == 0)
            softSelected = true;
        else if (type == 1)
            businessSelected = true;
        else if (type == 2)
            luxurySelected = true;

        currentOrder.setCarType(getSpecarType());
        ygCost();
    }

    @Override
    public void mapCenterChange(LatLng target) {
        LogUtil.log("home", "百度地图中心点位置变化:" + target.toString());
        currentLocAddr.setLatLng(target);
        currentOrder.setStartLat(target.latitude + "");
        currentOrder.setStartLng(target.longitude + "");

        refreshAreaCarList(currentOrder.getOrderCarType(), target);

        view.refreshStartMsg(" 获取中... ");
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(target));
    }

    @Override
    public void endAddrChange(AddressInfo info) {
        if (info == null)
            return;

        endAddressInfo = info;
        currentOrder.setEndLat(info.getLati());
        currentOrder.setEndLng(info.getLongi());
        currentOrder.setEndAddr(info.getAddr() + info.getName());

        view.refreshEndMsg(info.getName());

        ygCost();
    }

    @Override
    public void startAddrChange(AddressInfo startInfo) {
        if (startInfo == null)
            return;
        if (!StringUtils.isEmpty(startInfo.getName()))
            view.refreshStartMsg(startInfo.getName());
        view.refreshBdMapCenter(startInfo.getLatLng());
        refreshLocType(MainPresenterImpl.MODE_MAP_DIY);
    }

    @Override
    public void dateChange(String dateStr) {
        String date = AppManger.getInstance().getString(R.string.go_now);
        if (!StringUtils.isEmpty(dateStr)) {
            Date orderGoDate = ModuleUtils.getTimpikerDate(dateStr);
            if (orderGoDate != null)
                currentOrder.setBookDate(orderGoDate);

            String friendly_time = ModuleUtils.getFridenlyTime(orderGoDate);
            if (!StringUtils.isEmpty(friendly_time))
                date = friendly_time;
        } else {
            currentOrder.setBookDate(null);
        }

        view.refreshCfDate(date);
    }

    @Override
    public void tipChange(String tip) {
        if (!StringUtils.isEmpty(tip)) {
            currentOrder.setOrderTip(tip);
            view.refreshTip(tip);
        }
    }

    @Override
    public void phoneChange(String phone) {
        String desc = AppManger.getInstance().getString(R.string.lianxiwo);
        if (!StringUtils.isEmpty(phone)) {
            currentOrder.setPassgerPhone(phone);
            desc = phone.substring(phone.length() - 5);
        } else {
            currentOrder.setPassgerPhone(null);
        }
        view.refreshCoPhone(desc);
    }

    @Override
    public void beforeCallCar() {
        //准备修改
        if (!AppManger.getInstance().isLogin()) {
            view.showTip("请登录后叫车");
            return;
        }

        if (currentOrder.getOrderCarType() == Constants.CARTYPE_SPECAR && !softSelected && !businessSelected && !luxurySelected) {
            view.showTip(AppManger.getInstance().getString(R.string.qingxuanzhongcheliangleixing));
            return;
        }


        if (!StringUtils.isEmpty(currentOrder.getBookDate()))
            callCar();
        else {
            view.showWaitingTip("叫车中..", false);
            checkNotFinishOrder();
        }
    }

    @Override
    public void checkNotFinishOrder() {
        interactor.checkNotFinishOrder(AppManger.getInstance().user.getWorkNo(), new ApiWorks.ResponseListener<ApiCommonResult>() {
            @Override
            public void onResponse(ApiCommonResult apiCommonResult) {
                view.dissWaitingTip();
                if (apiCommonResult != null && apiCommonResult.getCode() == 0) {
                    if (!StringUtils.isEmpty(apiCommonResult.getData()))
                        view.showNotFinishOrder(apiCommonResult.getDesc(), apiCommonResult.getData());
                    else
                        view.showTip(apiCommonResult.getDesc());
                } else
                    callCar();
            }
        });
    }

    @Override
    public void callCar() {
        currentOrder.setCreateDate(new Date());
        if (StringUtils.isEmpty(currentOrder.getPassgerPhone()))
            currentOrder.setPassgerPhone(AppManger.getInstance().user.getPhone());

        if (currentOrder.getOrderCarType() == Constants.CARTYPE_TAXI)
            currentOrder.setCarType(0);

        if (isSsOrder)
            currentOrder.setBookDate(null);

        try {
            LatLng latLng = new LatLng(Double.parseDouble(currentOrder.getStartLat()), Double.parseDouble(currentOrder.getStartLng()));
            AppConfig.remberLastLocation(BaseApplication.getInstance().getApplicationContext(), latLng);
        } catch (Exception e) {
        }

        view.goPrePage(currentOrder);
    }

    @Override
    public void ygCost() {
        if (currentOrder.getOrderCarType() == Constants.CARTYPE_SPECAR
                && !StringUtils.isEmpty(currentOrder.getStartAddr()) && !StringUtils.isEmpty(currentOrder.getEndAddr())) {
            view.showSpecarPayView(true);
            interactor.ygCost(getEastCostType(), currentOrder, new ApiWorks.ResponseListener<ESpecarCost>() {
                @Override
                public void onResponse(ESpecarCost eSpecarCost) {

                    if (eSpecarCost != null && eSpecarCost.getReturnList() != null)
                        view.refreshYgCost(eSpecarCost.getReturnList().getTotalPrice());
                }
            });
        }
    }

    @Override
    public AddressInfo getStartAddr() {
        return currentLocAddr;
    }

    @Override
    public AddressInfo getEndAddr() {
        return endAddressInfo;
    }

    @Override
    public Order getCurrentOrder() {
        return currentOrder;
    }

    @Override
    public String getPsPhone() {
        String phone = currentOrder.getPassgerPhone();
        if (!StringUtils.isEmpty(phone) && phone.equals(AppManger.getInstance().user.getPhone()))
            phone = null;
        return phone;
    }

    @Override
    public void checkSs(boolean isSs) {
        if (isSs) {
            isSsOrder = true;
            view.showYyView(false);
        } else {
            isSsOrder = false;
            view.showYyView(true);
        }
    }

    @Override
    public MainInteractor createInteractor() {
        return new MainInteractorImpl();
    }


    //用户信息刷新以后
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handRefreshUserEvent() {
        view.refreshAfterLogin(AppManger.getInstance().user);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handOtherLogin(OtherLoginResponse otherLoginResponse){
        view.showTip(otherLoginResponse.getDesc());
        if (otherLoginResponse.getType().equals(OtherLoginResponse.TYPE_EXIT)) {
            AppManger.getInstance().loginOut();
            view.refreshAfterLogin(null);
            AppManger.getInstance().showMainPage();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handLoginError(RLoginEvent rLoginEvent) {
        view.refreshAfterLogin(null);
    }


    //处理定位信息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handLocationEvent(LocationEvent event) {
        BDLocation location = event.getLocation();
        lastLatlngLoc = new LatLng(location.getLatitude(), location.getLongitude());
        LogUtil.log("home", "收到定位信息：" + lastLatlngLoc.toString());
        if (currentMapMode == MODE_MAP_LOC && fristRefreshMap)
            view.refreshBdMapCenter(lastLatlngLoc);
    }


    private int getEastCostType() {
        if (softSelected) {
            return Constants.CARTYPE_SPECAR_SOFT;
        }
        if (businessSelected) {
            return Constants.CARTYPE_SPECAR_BUSINESS;
        }
        if (luxurySelected) {
            return Constants.CARTYPE_SPECAR_HAOHUA;
        }
        return Constants.CARTYPE_SPECAR_SOFT;
    }

    private int getSpecarType() {
        int type = 0x00;
        if (softSelected) {
            type = type | 0x01;
        }
        if (businessSelected) {
            type = type | 0x02;
        }
        if (luxurySelected) {
            type = type | 0x04;
        }
        return type;
    }
}
